package config

import (
	"go.uber.org/zap"
	"gopkg.in/yaml.v3"
	"log"
	"os"
	"path"
)

type Conf struct {
	Svc       server      `yaml:"server"`
	DB        database    `yaml:"database"`
	Jwt       jwt         `yaml:"jwt"`
	LogConfig logConfig   `yaml:"log"`
	Ws        ws          `yaml:"ws"`
	MiniApp   WeAppConfig `yaml:"miniApp"`
}

type server struct {
	Port           int    `yaml:"port"`
	RunMode        string `yaml:"runMode"`
	LogLevel       string `yaml:"logLevel"`
	EnabledSwagger bool   `yaml:"enabledSwagger"`
}

type database struct {
	Type            string `yaml:"type"`
	Host            string `yaml:"host"`
	Port            string `yaml:"port"`
	UserName        string `yaml:"username"`
	Password        string `yaml:"password"`
	DbName          string `yaml:"dbname"`
	MaxIdleConn     int    `yaml:"max_idle_conn"`
	MaxOpenConn     int    `yaml:"max_open_conn"`
	ConnMaxLifetime int    `yaml:"conn_max_lifetime"`
}

type jwt struct {
	Secret string `yaml:"secret"`
	JwtTtl int    `yaml:"jwt_ttl"`
}

type ws struct {
	TimerInterval int     `yaml:"timerInterval"`
	VisitorExpire float64 `yaml:"visitorExpire"`
}

type logConfig struct {
	Enabled  bool     `yaml:"enabled"`
	LogMode  string   `yaml:"logMode"`
	FilePath string   `yaml:"filePath"`
	Filtered []string `yaml:"filtered"`
}

// WeAppConfig 微信小程序配置
type WeAppConfig struct {
	AppID     string `yaml:"appId"`
	AppSecret string `yaml:"appSecret"`
}

// 初始化app配置
func InitAppConfig(dataFile string, logger *zap.Logger) *Conf {
	// 解决相对路经下获取不了配置文件问题
	//_, filename, _, _ := runtime.Caller(0)
	filePath := path.Join("", dataFile)

	//filePath := dataFile
	_, err := os.Stat(filePath)
	if err != nil {
		logger.Error("config file path not exist",
			zap.String("path", filePath), // 添加路径作为字符串字段
			zap.Error(err),               // 如果有错误对象，添加错误信息
		)
		panic("config file path " + filePath + " not exist")
	}
	yamlFile, err := os.ReadFile(filePath)
	if err != nil {
		logger.Error("yamlFile.Get err    ", zap.Error(err))
		panic(err.Error())
	}
	c := new(Conf)
	err = yaml.Unmarshal(yamlFile, &c)
	if err != nil {
		log.Printf("Unmarshal: %v", err)
		panic("Unmarshal:" + err.Error())
	}
	logger.Info("加载配置成功~")
	return c
}
